package com.tajiang.business.order.fragment;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.gprinter.aidl.GpService;
import com.gprinter.command.GpCom;
import com.gprinter.io.GpDevice;
import com.gprinter.io.PortParameters;
import com.gprinter.save.PortParamDataBase;
import com.gprinter.service.GpPrintService;
import com.tajiang.business.R;
import com.tajiang.business.bluetooth.ListViewAdapter;
import com.tajiang.business.bluetooth.utils.BTPrintUtils;
import com.tajiang.business.common.adapter.EmptyViewAdapter;
import com.tajiang.business.common.application.TJApp;
import com.tajiang.business.common.dialog.DialogWithTwoButton;
import com.tajiang.business.common.fragment.BaseFragment;
import com.tajiang.business.common.utils.BottomCallBackInterface;
import com.tajiang.business.common.utils.CommandTools;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.utils.PostDataTools;
import com.tajiang.business.common.utils.SharedPreferencesUtils;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.common.widget.ProgressDialog;
import com.tajiang.business.model.ApartmentZone;
import com.tajiang.business.model.Building;
import com.tajiang.business.model.Order;
import com.tajiang.business.model.Pager;
import com.tajiang.business.order.adapter.OrderMenuListAdapter;
import com.tajiang.business.order.dialog.OrderPrintingDialog;
import com.tajiang.business.order.view.OrderLoadMoreFooterView;
import com.tajiang.business.order.view.OrderRefreshHeadView;
import com.tajiang.business.order.view.popwindow.SelectApartmentPopWindow;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.tajiang.business.setting.activity.PrintsettingActivity.DEFAULT_PRINTER_NUM;

/**
 * 订单打印
 */
public class OrderFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener{

    public static OrderFragment instance = null;
    private ProgressDialog progressDialog;// 进度条对话框

    private final static int DEFAULT_REFRESH_TIME = 3000; //3秒延时打印第二个订单

    @BindView(R.id.swipe_refresh_header)
    OrderRefreshHeadView swipeRefreshHeader;

    @BindView(R.id.swipe_load_more_footer)
    OrderLoadMoreFooterView swipeLoadMoreFooter;

    @BindView(R.id.swipe_to_load_layout)
    SwipeToLoadLayout swipeToLoadLayout;

    @BindView(R.id.ll_show_dorm_list)
    LinearLayout llShowDormList;

    @BindView(R.id.fragment_order_title_left)
    TextView tvCurrentBuilding;

    @BindView(R.id.fragment_order_title_right)
    TextView btnPrintAll;

    @BindView(R.id.swipe_target)
    RecyclerView listView;

    @BindView(R.id.fragment_order_view)
    View lineView;

    private MyCountDownTimer myCountDownTimer;

    private String currentApartmentId = "";  //实时更新当前宿舍区id

    private EmptyViewAdapter emptyViewAdapter;  //订单列表为空的时候显示空Adapter

    private OrderPrintingDialog OnPrintingDialog;

    private OrderMenuListAdapter mAdapter;
    private Context mContext;
    private List<Order> orderList = new ArrayList<Order>();
    private int pageNumber = 1;//当前页

    private List<Building> apartmentList;
    private int printerStatus = 0;//打印接状态
    private int printType= 1;// 1-单个打印 0-打印所有
    private int printPosition = 0;//当前打印位置，单个打印时用

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        instance = this;
        mContext = this.getContext();

        initPortParam(); //获取上次已连接的（设备名称）和（连接状态）
        connection();  //连接打印机服务
        initApartmentList();
    }

    @Override
    protected void initTopBar() {

        hidenTopBar();
    }

    @Override
    protected void initLayout() {

        setContentView(R.layout.fragment_order);

        //开始连接打印机
        int isFirst = Integer.parseInt(SharedPreferencesUtils.get(SharedPreferencesUtils.FIRST_CONNECT_PRINTER, 0).toString());
        if(isFirst == 1){
            myhandler.sendEmptyMessage(0);
        }

    }

    /**
     * 初始化请求参数
     */
    @Override
    protected void initData() {

        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
        swipeToLoadLayout.setLoadMoreEnabled(false);

        this.OnPrintingDialog = new OrderPrintingDialog(getActivity());

        mAdapter = new OrderMenuListAdapter(getActivity(), Order.ORDER_PRINT, orderList, new BottomCallBackInterface.OnBottomClickListener() {

            @Override
            public void onBottomClick(View v, int position) {

                final Order order = orderList.get(position);
                if(v.getId() == R.id.item_order_menu_img_time){

                    if(order.isChecked()){
                        order.setChecked(false);
                    }else{
                        order.setChecked(true);
                    }

                }else if(v.getId() == R.id.item_order_menu_confirm){

                    try{
                        printType = 1;
                        printPosition = position;
//                        getPrinterStatus();
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    OnPrintSingleOrder();
                }else if(v.getId() == R.id.item_order_menu_phone){

                    DialogWithTwoButton.showDialog(getActivity(), "取消", "确认", "确认拨打电话: " + order.getReceiverPhone(), new DialogWithTwoButton.DialogCallback() {

                        @Override
                        public void callback(int position) {

                            if(position == 1){

                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + order.getReceiverPhone()));
                                startActivity(intent);
                            }
                        }
                    });
                }
            }
        });

        listView.setLayoutManager(new LinearLayoutManager(getActivity()));
        listView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext())
                .color(getResources().getColor(R.color.gray)).size(36).build());
        listView.setItemAnimator(new DefaultItemAnimator());

        this.emptyViewAdapter = new EmptyViewAdapter(getContext(), R.layout.layout_empty_order_view);

        listView.setAdapter(emptyViewAdapter);

        onRefresh();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);

        getActivity().registerReceiver(PrinterStatusBroadcastReceiver, new IntentFilter(GpCom.ACTION_DEVICE_REAL_STATUS));
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {

        pageNumber = 1;
        PostDataTools.order_list(getActivity(), Order.ORDER_PRINT, currentApartmentId, pageNumber, swipeToLoadLayout, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                Pager<Order> pager = (Pager<Order>) object;
                List<Order> newOrderList = pager.getList();

                orderList.clear();
                orderList.addAll(newOrderList);

                updateMyRecyclerView(orderList);

                if (newOrderList.size() >= Order.PAGE_SIZE){
                    pageNumber = 2;
                    swipeToLoadLayout.setLoadMoreEnabled(true);
                }
            }
        });
    }

    /**
     * 上拉获取下一页
     */
    @Override
    public void onLoadMore() {

        PostDataTools.order_list(getActivity(), Order.ORDER_PRINT, currentApartmentId, pageNumber, swipeToLoadLayout, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                Pager<Order> pager = (Pager<Order>) object;
                List<Order> newOrderList = pager.getList();

                orderList.addAll(newOrderList);
                mAdapter.notifyDataSetChanged();

                if (newOrderList.size() >= Order.PAGE_SIZE){
                    ++pageNumber;
                    swipeToLoadLayout.setLoadMoreEnabled(true);
                }else{
                    swipeToLoadLayout.setLoadMoreEnabled(false);
                }
            }
        });
    }

    /**
     * 点击宿舍区，弹出宿舍列表
     */
    @OnClick(R.id.ll_show_dorm_list)
    public void onSelectDormListClick() {

        setDropListTextViewRightImg(R.drawable.order_arrow);
        initCeoPopWindow();
    }

    /**
     * 获取楼栋
     * @return
     */
    private SelectApartmentPopWindow selectApartmentPopWindow;
    private void initCeoPopWindow() {

        //通过布局注入器，注入布局给View对象
        View myView = getActivity().getLayoutInflater().inflate(R.layout.layout_pop_dorm_list, null);
        //通过view 和宽·高，构造PopopWindow
        if (selectApartmentPopWindow == null) {

            selectApartmentPopWindow = new SelectApartmentPopWindow(getActivity()
                    , myView
                    , apartmentList
                    , LinearLayout.LayoutParams.MATCH_PARENT
                    , LinearLayout.LayoutParams.MATCH_PARENT
                    , true);

            //点击全部宿舍楼，重新加载全部订单
            selectApartmentPopWindow.setOnSelectAllApartmentListener(new SelectApartmentPopWindow.OnSelectAllApartmentListener() {
                @Override
                public void onSelectAllApartment() {

                    tvCurrentBuilding.setText("全部宿舍楼");
                    currentApartmentId = "";
                    selectApartmentPopWindow.dismiss();
                    onRefresh();
                }
            });

            selectApartmentPopWindow.setSelectApartmentClickListener(new SelectApartmentPopWindow.OnSelectApartmentListener() {

                @Override
                public void onSelectApartmentClick(String apartmentId1, int position) {

                    String currentBuilding = apartmentList.get(position).getName();
                    currentApartmentId = apartmentList.get(position).getId();
                    tvCurrentBuilding.setText(currentBuilding);
                    onRefresh();
                }
            });
            selectApartmentPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

                @Override
                public void onDismiss() {

                    setDropListTextViewRightImg(R.drawable.order_back);
                }
            });
        }

        selectApartmentPopWindow.showAsDropDown(llShowDormList, 0, 0);
    }

    public void setDropListTextViewRightImg(int resId) {

        Drawable drawable = getResources().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tvCurrentBuilding.setCompoundDrawables(null, null, drawable, null);
    }

    /**
     * 获取打印机打印状态
     */
    public boolean getPrinterStatus() throws Exception{

        BTPrintUtils.mConnectState = 0;

        if (null == mGpService) {
            mGpService = TJApp.getInstance().getmGpService();
        }

        if (mGpService == null) {
            OnPrintingDialog.dismiss();
            myCountDownTimer.cancel();
            CommandTools.showLong("请首先配置打印机");
            return false;
        }

        // 这里增加判断，是否连接正常 @20170506 by me
        int li_PrinterConnectStatus = mGpService.getPrinterConnectStatus(0);

        if (3 != li_PrinterConnectStatus && 5 != li_PrinterConnectStatus) {
            OnPrintingDialog.dismiss();
            myCountDownTimer.cancel();
            CommandTools.showLong("打印机已断开,请到【设置】-【打印设置】中重新连接");
            return false;
        }else{
            BTPrintUtils.mConnectState = 1;
        }

        try {
            mGpService.queryPrinterStatus(0, 500, MAIN_QUERY_PRINTER_STATUS);
        } catch (RemoteException e1) {
            e1.printStackTrace();
        }

        return true;
    }

    /**
     * 打印单个订单
     * 检查是否清空了订单列表
     *
     */
    public void OnPrintSingleOrder() {

        try{

            boolean flag = getPrinterStatus();
            if(flag == false){
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        OnPrintingDialog.show();
        Order order = orderList.get(printPosition);

        String rel = BTPrintUtils.getInstance().printSinglePage(getActivity(), order);

        OnPrintingDialog.dismiss();
        if (rel != null && rel.equals(BTPrintUtils.PRINT_SUCCESS)) {
            updateOrderPrintState(order.getOrderId());
        }
    }

    private Timer timer_ALL = null;
    private int timer_cnt = 0;

    @OnClick(R.id.fragment_order_title_right)
    public void onPrintAllClick(){

        printType = 0;
        OnPrintAllOrder();
    }

    /**
     * 延时打印全部
     */
    private void OnPrintAllOrder() {

        try{

            boolean flag = getPrinterStatus();
            if(flag == false){
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        if (timer_cnt > 0) {
            return;
        }

        timer_cnt ++ ;
        timer_ALL = new Timer();
        // 调度一个task，经过delay(ms)后开始进行调度，仅仅调度一次即可.
        timer_ALL.schedule(new TimerTask() {

            @Override
            public void run() {

                timer_cnt = 0;
            }
        }, 2000);

        try {
            if (orderList.size() > 0) {

                OnPrintingDialog.show();

                myCountDownTimer = new MyCountDownTimer(DEFAULT_REFRESH_TIME, orderList);
                myCountDownTimer.start();
            } else {
                ToastUtils.showShort("当前没有订单可以打印");
            }
        } catch (Exception ex) {
            OnPrintingDialog.dismiss();
        }
    }

    /**
     * 对订单的一系列操作之后更新当前订单数据
     *
     * @param newOrderList
     */
    private void updateMyRecyclerView(List<Order> newOrderList) {

        try {
            if (newOrderList != null) {

                if (newOrderList.size() < 1) {
                    listView.setAdapter(emptyViewAdapter);
                } else {
                    listView.setAdapter(mAdapter);
                }

                mAdapter.notifyDataSetChanged();
            }
        } catch (Exception ex) {
            Log.d("【updateMyRecyclerView】", "异常：" + ex.getMessage());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            Log.e("【onDestroy】", "onDestroy-->注销事件绑定..");
            instance.getContext().unregisterReceiver(PrinterStatusBroadcastReceiver);
            if (PServiceConn != null) {
                instance.getContext().unbindService(PServiceConn); // unBindService
            }
        } catch (Exception ex) {
            Log.d("【onDestroy】", "异常：" + ex.getMessage());
        }
    }

    /**
     * 更新订单打印状态
     */
    private void updateOrderPrintState(final String orderId) {

        if(printerStatus != GpCom.STATE_NO_ERR){
            return;
        }

        if(TextUtils.isEmpty(orderId)){
            return;
        }

        LogUtils.e("打印的订单ID：" + orderId);

        PostDataTools.order_print(getActivity(), orderId, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                for(int i=0; i<orderList.size(); i++){

                    Order order = orderList.get(i);
                    if(orderId.equals(order.getOrderId())){
                        orderList.remove(i);
                        --i;
                        break;
                    }
                }

                swipeToLoadLayout.setLoadMoreEnabled(false);
                mAdapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    public void reFreshCurrentPageData() {
        super.reFreshCurrentPageData();

        onRefresh();
    }

    /**
     * 定时刷新页面
     */
    public void refreshOrderBySpecificTime() {

    }

    private PortParameters mPortParams[] = new PortParameters[DEFAULT_PRINTER_NUM];
    private int mPrinterId = BTPrintUtils.PRINTER_ID;     // 默认的打印机ID
    public boolean isConnected = false; // 打印机连接状态
    private String deviceName;   //实时更新选择搜索出来的设备名称
    private GpService mGpService;
    private PrinterServiceConnection PServiceConn = null;
    private List<Map<String, Object>> mList = null;
    private static final int MAIN_QUERY_PRINTER_STATUS = 0xfe;

    /**
     * 从数据库获取上次存储组的已选设备的相关状态参数
     */
    private void initPortParam() {
        PortParamDataBase database = new PortParamDataBase(this.getContext());
        mPortParams[mPrinterId] = new PortParameters();
        mPortParams[mPrinterId] = database.queryPortParamDataBase("" + mPrinterId);
        mPortParams[mPrinterId].setPortOpenState(false);
        this.deviceName = mPortParams[mPrinterId].getUsbDeviceName();
        mList = getOperateItemData();
//        Log.d("【OF】【x】", "initPortParam.mPrinterId = " + mPrinterId);
//        Log.d("【OF】【x】", "initPortParam.deviceName = " + deviceName);
//        Log.d("【OF】【x】", "initPortParam.mList = " + mList.toString());
    }

    /**
     * 打印机重新连接过程!!!
     */
    public Handler myhandler = new Handler() {

        public void dispatchMessage(android.os.Message msg) {

            try {
                switch (msg.what) {
                    case 0: // 显示等待窗口
                        progressDialog = new ProgressDialog(instance.getContext());
                        progressDialog.setCancelable(true);
                        progressDialog.setMessage("连接打印机..");
                        progressDialog.setOnCancelListener(cancelListener);
                        progressDialog.show();
                        // 注册绑定事件
                        registerPrinterStatueBroadcast();
                        Log.i("【OF】", "myhandler.connectOrDisConnectToDevice(" + mPrinterId + ")");
                        connectOrDisConnectToDevice(mPrinterId);
                        break;
                    case 100://成功
                        BTPrintUtils.mConnectState = 1;
                        progressDialog.dismiss();// 取消对话框
                        CommandTools.showShort("打印机连接成功");
                        break;
                    case 400://失败
                        BTPrintUtils.mConnectState = 0;
                        unBindBTStatusReceiver();
                        progressDialog.dismiss();// 取消对话框
                        CommandTools.showShort("连接失败，请重新连接!");
                    case 401://失败
                        BTPrintUtils.mConnectState = 0;
                        unBindBTStatusReceiver();
                        progressDialog.dismiss();// 取消对话框
                        CommandTools.showShort("打印机连接失败");
                    case 0x1100:

                        if(printType == 1){
                            OnPrintSingleOrder();
                        }else{
                            myCountDownTimer.printSingle();
//                            OnPrintAllOrder();
                        }
                        break;
                    default:
                        progressDialog.dismiss();
                        break;
                }
            } catch (Exception ex) {
                Log.d("【onDestroy】", "异常：" + ex.getMessage());
            }
        }
    };

    private DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            // Toast.makeText(mContext, "进度条被取消", Toast.LENGTH_LONG) .show();
            mContext.unregisterReceiver(PrinterStatusBroadcastReceiver);
        }
    };

    /**
     * 当前Fragment连接蓝牙
     */
    private void connection() {

        PServiceConn = new PrinterServiceConnection();
        Intent intent = new Intent(OrderFragment.instance.getContext(), GpPrintService.class);
        mContext.bindService(intent, PServiceConn, Context.BIND_AUTO_CREATE); // bindService
    }

    /**
     * 注册广播，接收打印机连接状态变更
     */
    private void registerPrinterStatueBroadcast() {

        IntentFilter filter = new IntentFilter();
        filter.addAction(GpCom.ACTION_CONNECT_STATUS);
//        filter.addAction(GpCom.ACTION_DEVICE_REAL_STATUS);
        getActivity().registerReceiver(PrinterStatusBroadcastReceiver, filter);
    }

    /**
     * 广播“打印机连接状态变更
     */
    private BroadcastReceiver PrinterStatusBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            Log.v("test", intent.getAction());
            try {

                if (GpCom.ACTION_CONNECT_STATUS.equals(intent.getAction())) {

                    int type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0);
                    int id = intent.getIntExtra(GpPrintService.PRINTER_ID, 0);
                    Log.d("【状态变更】BroadcastReceiver", "connect status ==> " + type);

                    if (type == GpDevice.STATE_CONNECTING) {
                        mPortParams[id].setPortOpenState(false);
                        Map<String, Object> map;
                        map = mList.get(id);
                        map.put(ListViewAdapter.STATUS, getString(R.string.connecting));
                        mList.set(id, map);
                        map.put(ListViewAdapter.DEVICE_NAME, deviceName);
                        Log.d("【BroadcastReceiver】", "正在连接 --->" + map.toString());
                    } else if (type == GpDevice.STATE_NONE) {//变成无状态的状态。。
                        mPortParams[id].setPortOpenState(false);
                        Map<String, Object> map;
                        map = mList.get(id);
                        map.put(ListViewAdapter.STATUS, getString(R.string.connect));
                        mList.set(id, map);
                        myhandler.sendEmptyMessage(401);
                    } else if (type == GpDevice.STATE_VALID_PRINTER) {
                        mPortParams[id].setPortOpenState(true);
                        Map<String, Object> map;
                        map = mList.get(id);
                        map.put(ListViewAdapter.STATUS, getString(R.string.cut));
                        mList.set(id, map);
                        Log.d("【BroadcastReceiver】", "连接完成 --->" + map.toString());
                        // 这里重新开始打印：
                        myhandler.sendEmptyMessage(100);
                    } else if (type == GpDevice.STATE_INVALID_PRINTER) {
                        myhandler.sendEmptyMessage(400);
                    }
                } else if (GpCom.ACTION_DEVICE_REAL_STATUS.equals(intent.getAction())) {

                    // 业务逻辑的请求码，对应哪里查询做什么操作
                    int requestCode = intent.getIntExtra(GpCom.EXTRA_PRINTER_REQUEST_CODE, -1);
                    // 判断请求码，是则进行业务操作
                    if (requestCode == MAIN_QUERY_PRINTER_STATUS) {

                        printerStatus = intent.getIntExtra(GpCom.EXTRA_PRINTER_REAL_STATUS, 16);
                        String str = "";
                        if (printerStatus == GpCom.STATE_NO_ERR) {
                            str = "打印机正常";
                        } else {

                            if ((byte) (printerStatus & GpCom.STATE_OFFLINE) > 0) {
                                str += "请到【设置】-【打印设置】中重新连接";
                            }
                            if ((byte) (printerStatus & GpCom.STATE_PAPER_ERR) > 0) {
                                str += "缺纸";
                            }
                            if ((byte) (printerStatus & GpCom.STATE_COVER_OPEN) > 0) {
                                str += "打印机开盖";
                            }
                            if ((byte) (printerStatus & GpCom.STATE_ERR_OCCURS) > 0) {
                                str += "打印机出错";
                            }
                            if ((byte) (printerStatus & GpCom.STATE_TIMES_OUT) > 0) {
                                str += "查询超时";
                            }

                            if(printType != 1){
                                myCountDownTimer.cancel();
                            }

                            OnPrintingDialog.dismiss();
                            CommandTools.showLong("打印机异常：" + str);
                        }

                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                Log.d("【PSBroadcastReceiver】", "异常：" + ex.getMessage());
            }
        }
    };

    private List<Map<String, Object>> getOperateItemData() {

        Map<String, Object> map;
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            for (int i = 0; i < DEFAULT_PRINTER_NUM; i++) {
                map = new HashMap<String, Object>();
                if (mPortParams[i].getPortOpenState() == false) {
                    this.isConnected = false;
                    map.put(ListViewAdapter.STATUS, getString(R.string.connect));
                } else {
                    this.isConnected = true;
                    map.put(ListViewAdapter.STATUS, getString(R.string.cut));
                }
                String str = getPortParamInfoString(mPortParams[i]);
                map.put(ListViewAdapter.DEVICE_NAME, this.deviceName);
                map.put(ListViewAdapter.INFO, str);
                map.put(ListViewAdapter.BT_ENABLE, "enable");
                list.add(map);
            }
        } catch (Exception ex) {
            Log.d("【getOperateItemData】", "异常：" + ex.getMessage());
        }

        return list;
    }

    private String getPortParamInfoString(PortParameters Param) {

        String info = new String();
        info = getString(R.string.port);
        int type = Param.getPortType();
        Log.d("TEST", "Param.getPortType() " + type);
        if (type == PortParameters.BLUETOOTH) {
            info += getString(R.string.bluetooth);
            info += "  " + getString(R.string.address);
            info += Param.getBluetoothAddr();
        } else {
            info = getString(R.string.init_port_info);
        }
        return info;
    }

    /**
     * 绑定bt打印机连接状态的变更
     */
    private void unBindBTStatusReceiver() {

        try {
            mContext.unregisterReceiver(PrinterStatusBroadcastReceiver);
            if (PServiceConn != null) {
                mContext.unbindService(PServiceConn); // unBindService
            }
        } catch (Exception ex) {
            Log.i("【OF】", "-unBindBTStatusReceiver()-Exception:" + ex.getMessage());
        }
    }

    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("【OF】", "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
        }
    }

    /// TODO 这里是硬件操作，具体看 PrinterStatusBroadcastReceiver 的绑定事件
    void connectOrDisConnectToDevice(int PrinterId) {
        try {
            mPrinterId = PrinterId;
            int rel = 0;
            Log.e("【OF】", "【重新连接】(" + PrinterId + ")" + String.valueOf(mPortParams[PrinterId].getPortOpenState()));

            try {
                mGpService.closePort(mPrinterId);
            } catch (RemoteException e) {
                Log.e("【OF】", "【重新连接】(" + PrinterId + ")mGpService.closePort异常：" + e.getMessage());
            }

            try {
                Thread.sleep(80);
            } catch (Exception e) {
            }

            if (mPortParams[PrinterId].getPortOpenState() == false) {   //如果未连接，则连接
                if (CheckPortParamters(mPortParams[PrinterId])) {
                    switch (mPortParams[PrinterId].getPortType()) {
                        case PortParameters.BLUETOOTH:
                            try {
                                rel = mGpService.openPort(PrinterId, mPortParams[PrinterId].getPortType(), mPortParams[PrinterId].getBluetoothAddr(), 0);
                            } catch (RemoteException e) {
                                Log.e("【TEAT】", "【重新连接】(" + PrinterId + ")异常：" + e.getMessage());
                            }
                            try {
                                Thread.sleep(30);
                            } catch (Exception e) {
                            }
                            break;
                    }
                    GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];

                    Log.e("【OF】", "GpCom.ERROR_CODE.r=" + r);

                    if (r != GpCom.ERROR_CODE.SUCCESS) {
                        if (r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
                        } else {
                            Log.e("【OF】", "【重新连接】(" + PrinterId + ")失败：" + GpCom.getErrorText(r));
                        }
                    }
                } else {
                    Log.e("【TEST重新连接】", "【重新连接】(" + PrinterId + ")错误：" + getString(R.string.port_parameters_wrong));
                }
            } else { //如果还是处于连接状态，则断开连接...
                Log.d("【OF】", "还是处于连接状态,重新尝试..");
                // myhandler.sendEmptyMessage(401);
                try {
                    rel = mGpService.openPort(PrinterId, mPortParams[PrinterId].getPortType(), mPortParams[PrinterId].getBluetoothAddr(), 0);
                } catch (RemoteException e) {
                    Log.e("【TEAT】", "【重新连接】(" + PrinterId + ")异常：" + e.getMessage());
                }
                try {
                    Thread.sleep(30);
                } catch (Exception e) {
                }
            }
        } catch (Exception ex) {
            Log.e("【OF】【异常】", "【connectOrDisConnectToDevice()异常：(" + PrinterId + "):" + ex.getMessage());
        }
    }

    public boolean CheckPortParamters(PortParameters param) {

        boolean rel = false;
        int type = param.getPortType();

        if (type == PortParameters.BLUETOOTH) {

            if (!param.getBluetoothAddr().equals("")) {
                rel = true;
            }
        }
        return rel;
    }

    /**
     * Class
     * 延时打印订单
     */
    class MyCountDownTimer extends CountDownTimer {

        private List<Order> printList;  //打印的订单
        private String orderId;
        private int currentPosition;
        private boolean isFinishRequest;

        public MyCountDownTimer(long countDownInterval, List<Order> orderList) {
            super((orderList.size() + 1) * countDownInterval, countDownInterval);
            this.printList = orderList;
            this.currentPosition = 0;
            this.isFinishRequest = false;
        }

        @Override
        public void onFinish() {
            LogUtils.e("打印完毕。。。--> " + currentPosition);
            doRequest(0);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            LogUtils.e("延时打印 --> 当前序号：" + currentPosition);

            try{

                boolean flag = getPrinterStatus();
                if(flag == false){
                    doRequest(-1);
                    return;
                }
            }catch (Exception e){
                e.printStackTrace();
            }

            printSingle();
        }

        private void doRequest(int type) {

            OnPrintingDialog.dismiss();
            if (isFinishRequest == false) {

                myCountDownTimer.cancel();
                isFinishRequest = true;

                if(type == 0){
                    updateOrderPrintState(orderId);
                }
            }
        }

        /**
         * 打印当前序号 currentPosition 指示的位置;
         * currentPosition = 0 ,从上往下逐个打印.
         */
        public void printSingle() {

            if (currentPosition < printList.size()) {

                LogUtils.e("【518】printSingle()正在打印第几个：" + currentPosition);

                Order order = printList.get(currentPosition);

                try {

                    Thread.sleep(20);

                    String rel = BTPrintUtils.getInstance().printSinglePage(getActivity(), order);
                    if (rel != null && rel.equals(BTPrintUtils.PRINT_SUCCESS)) {

                        currentPosition += 1;
                        orderId = order.getOrderId();

                        if (currentPosition >= printList.size()) {
                            // 清空 订单队列
                            printList.clear();

                            doRequest(0);
                            return;
                        }
                    } else {
                        doRequest(-1);   //中间某个订单打印失败，提前结束，
                    }
                } catch (Exception ex) {
                    OnPrintingDialog.dismiss();
                    LogUtils.e("【OF】Exception(" + ex.getMessage() + ")");
                }
            }
        }
    }// END --> MyCountDownTimer


    private void initApartmentList() {

        PostDataTools.shop_apartment(getActivity(), new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                List<ApartmentZone> list = new ArrayList<ApartmentZone>();
                list.addAll((List<ApartmentZone>) object);

                //这里面需要对校区进行处理，暂时没改
                apartmentList = new ArrayList<Building>();
                for(int i=0; i<list.size(); i++){

                    ApartmentZone apartmentZone = list.get(i);
                    ArrayList<Building> buildingArrayList = (ArrayList<Building>) list.get(i).getList();

                    for(int k=0; k<buildingArrayList.size(); k++){

                        Building building = buildingArrayList.get(k);
                        building.setSchoolArea(apartmentZone.getName());
                    }

                    apartmentList.addAll(buildingArrayList);
                }

                if (apartmentList.size() == 1) {
                    tvCurrentBuilding.setText(apartmentList.get(0).getName());
                }
            }
        });
    }
}
